import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  All,
  Logger,
} from '@nestjs/common';
import { Response } from 'express';

@Catch() // 捕获所有异常
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionsFilter.name);

  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.status || 500; // 获取异常的状态码
    this.logger.error(
      `Exception occurred: ${exception.message}`,
      exception.stack,
    );
    // 返回一个统一的错误格式
    response.status(status).json({
      statusCode: status,
      message: exception.message || 'Internal Server Error',
      timestamp: new Date().toISOString(),
    });
  }
}
